<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">

          <a-col :md="8" :sm="24">
            <a-form-item label="日期">
              <a-date-picker
                placeholder="请选择日期"
                format="YYYY-MM-DD"
                style="width: 100%"
                @change="onChange"
                allow-clear
                v-model="queryParam.createdAt">
              </a-date-picker>
            </a-form-item>
          </a-col>

          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" class="btn_search_reset" @click="search"><a-icon type="search" />查询</a-button>
              <a-button style="margin-left: 8px" class="btn_search_reset" @click="reset"><a-icon type="reload" />重置</a-button>
              <a-button type="primary" class="btn_search_reset" @click="back(0)"><a-icon type="rollback"/>返回</a-button>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      size="default"
      :columns="columns"
      :data-source="fileDataSet"
      :rowKey="(record) => record.file"
    >
      <span slot="modelFile" slot-scope="text,record">
        <a @click="$refs.playForm.play(record)">播放</a>
      </span>

      <span slot="action" slot-scope="text, record">
        <a @click="downloadFile(record)" class="btn_edit">下载</a>
      </span>
    </a-table>

  </a-card>
</template>

<script>
  import { STable } from '@/components'
  import moment from 'moment'

  export default {
    components: {
      STable
    },

    data () {
      return {
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {}, // 查询参数
        columns: [ // 表头
          {
            title: '文件',
            dataIndex: 'file'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '150px',
            scopedSlots: { customRender: 'action' }
          }
        ],
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id'
        },
        confirmLoading: false,
        isConnection: false,
        mDownloadFileName: '',
        myId: '',
        ws: '',
        createdAt: null,
        fileDataSet: []
      }
    },

    methods: {
      queryFile (deviceCode, date) {
        if (!this.isConnection) {
          alert('网关连接失败，请刷新页面后重试！')
          return
        }
        this.ws.send(JSON.stringify({
          from: this.myId,
          to: deviceCode,
          cmd: 'QUERY_FILE',
          data: date
        }))
      },
      getFile (deviceCode, date) {
        if (!this.isConnection) {
          alert('网关连接失败，请刷新页面后重试！')
          return
        }

        this.ws.send(JSON.stringify({
          from: this.myId,
          to: deviceCode,
          cmd: 'GET_FILE',
          data: date
        }))
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      initList (arr) {
        arr = JSON.parse(arr)
        this.fileDataSet = []
        for (let i = 0; i < arr.length; i++) {
          this.fileDataSet.push({
            file: arr[i]
          })
        }
      },
      url (s) {
        const l = window.location
        return ((l.protocol === 'https:') ? 'wss://' : 'ws://') + l.hostname + ':82' + s
      },
      /**
       * 日期需单独转换
       */
      onChange (date, dateString) {
        if (date == null) {
          this.createdAt = []
        } else {
          this.createdAt = moment(date).format('YYYY-MM-DD')
        }
      },
      downloadFile (recoed) {
        const deviceCode = this.$route.params.deviceCode
        this.mDownloadFileName = recoed.file
        this.getFile(deviceCode, this.mDownloadFileName)
      },
      initWebsocket () {
        this.myId = this.randomNum(6)
        const wsUrl = this.url('/ws/gateway/' + this.myId)
        this.ws = this.ws || new WebSocket(wsUrl)
        this.ws.onmessage = this.onWebsocketMessage
        this.ws.onopen = this.onWebsocketOpen
        this.ws.onerror = this.onWebsocketError
        this.ws.binaryType = 'blob'
      },
      onWebsocketOpen () {
        this.isConnection = true
      },
      onWebsocketClose (e) {
      },
      onWebsocketMessage (e) {
        const data = e.data
        if (typeof data === 'string') {
          if (data === 'OFFLINE' || data === '') {
            this.$message.error('设备离线')
          } else {
            const responseData = JSON.parse(data)
            switch (responseData.cmd) {
              case 'REPLY_QUERY_FILE': // 回复列表
                const fileList = responseData.data
                this.initList(fileList)
                break
            }
          }
        } else if (typeof data === 'object') {
          // 文件
          this.download(data, this.mDownloadFileName)
        }
      },
      download (blob, saveName) {
        saveName = saveName || (new Date().getTime()) + '.wav'
        const reader = new FileReader()
        reader.readAsDataURL(blob) // 转换为base64，可以直接放入a表情href
        reader.onload = function (e) {
          // 转换完成，创建一个a标签用于下载
          const link = document.createElement('a')
          const body = document.querySelector('body')
          link.href = window.URL.createObjectURL(blob) //
          link.style.display = 'none' // 让这个a标签不可见
          link.download = saveName // 文件名称
          body.appendChild(link)
          link.click() // 创建了新的a标签之后模拟点击事件，开始传输文件
          body.removeChild(link) // 下载完成之后，移除按钮，垃圾回收，减少页面内存消耗
          window.URL.revokeObjectURL(link.href) // 移除
        }
      },
      onWebsocketError (e) {
      },
      onFinish () {
        this.getOneFile()
      },
      search () {
        const date = this.createdAt
        const deviceCode = this.$route.params.deviceCode
        if (deviceCode) {
          if (!date) {
            alert('请选择日期')
            return
          }
          this.queryFile(deviceCode, date)
        } else {
          this.back(0)
        }
      },
      back (index) {
        this.$router.push({ name: 'Console', params: { index: index } })
      },
      reset () {
        this.queryParam = {}
        this.createdAt = null
      }
    },
    mounted () {
      const deviceCode = this.$route.params.deviceCode
      if (!deviceCode) {
        this.$router.push({ name: 'Console', params: { index: '0' } })
      }
      this.initWebsocket()
    },
    destroyed () {
      if (this.ws) {
        this.ws.close()
      }
    }
  }
</script>

<style lang="less">
  .table-operator {
    margin-bottom: 18px;
  }
  button {
    margin-right: 8px;
  }
</style>
